//
//  AFNetworkUtils.m
//  WeiAiPin
//
//  Created by 猫王之王 on 1/7/21.
//  Copyright © 2021 tudu. All rights reserved.
//

#import "AFNetworkUtils.h"

#import "AFNetworkActivityIndicatorManager.h"


static NSMutableArray *_allSessionTask;
static NSString *netState;

@implementation AFNetworkUtils
+(NSURLSessionTask *)POST_RawToken:(NSString *)url body:(id)parameter head:(nullable NSDictionary <NSString *, NSString *> *)head success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = response;
//    session.requestSerializer =  [AFJSONRequestSerializer serializer];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 10.f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    
    
    NSUserDefaults * stand  = [NSUserDefaults standardUserDefaults];
    NSString * token = [stand objectForKey:@"token"];
    [session.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    
    [session.requestSerializer setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"requestKey"];
    NSString * timestr = [TKLTools getNomeTimeData];
    
    [session.requestSerializer setValue:timestr forHTTPHeaderField:@"timestsmp"];
    [session.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
    
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
//    NSLog(@"%@,%@,%@",url,session.requestSerializer.HTTPRequestHeaders,parameter);
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    [session.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error){
        return parameter;
    }];

    
    NSURLSessionTask *sesstionTask =  [session POST:url parameters:parameter headers:head progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
        NSLog(@"%@",error);
//        failure(@"网络异常");
        [[self allSessionTask] removeObject:task];

    }];

    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
    
}
//POST  Raw Json格式
+(NSURLSessionTask *) POST_Raw:(NSString *)url body:(id)parameter head:(nullable NSDictionary <NSString *, NSString *> *)head success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{

    
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = response;
//    session.requestSerializer =  [AFJSONRequestSerializer serializer];
    [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    session.requestSerializer.timeoutInterval = 10.f;
    [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    [session.requestSerializer setValue:@"Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==" forHTTPHeaderField:@"Authorization"];
    
    [session.requestSerializer setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"requestKey"];
    NSString * timestr = [TKLTools getNomeTimeData];
    
    [session.requestSerializer setValue:timestr forHTTPHeaderField:@"timestsmp"];
    [session.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
    
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
//   NSLog(@"%@,%@,%@",url,session.requestSerializer.HTTPRequestHeaders,parameter);
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

    [session.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error){
        return parameter;
    }];

    
    NSURLSessionTask *sesstionTask =  [session POST:url parameters:parameter headers:head progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
        NSLog(@"%@",error);
//        failure(@"网络异常");
        [[self allSessionTask] removeObject:task];

    }];

    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
}


+(NSURLSessionTask *)POST:(NSString *)url body:(id)parameters head:(nullable NSDictionary <NSString *, NSString *> *)head success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{

    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
       response.removesKeysWithNullValues = YES;

       AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
       session.responseSerializer = response;

       [session.requestSerializer willChangeValueForKey:@"timeoutInterval"];
       session.requestSerializer.timeoutInterval = 10.f;
       [session.requestSerializer didChangeValueForKey:@"timeoutInterval"];

       session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];

//       [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSUserDefaults * stand  = [NSUserDefaults standardUserDefaults];
    NSString * token = [stand objectForKey:@"token"];
    [session.requestSerializer setValue:token forHTTPHeaderField:@"Authorization"];
    
    [session.requestSerializer setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forHTTPHeaderField:@"requestKey"];
    NSString * timestr = [TKLTools getNomeTimeData];
    
    [session.requestSerializer setValue:timestr forHTTPHeaderField:@"timestsmp"];
    [session.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
    
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//       NSLog(@"%@",url);
       // 打开状态栏的等待菊花
       [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;


       NSURLSessionTask *sesstionTask =  [session POST:url parameters:parameters headers:head progress:^(NSProgress * _Nonnull uploadProgress) {

       } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
           success(responseObject);
           [[self allSessionTask] removeObject:task];
       } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
           [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
           NSLog(@"%@",error);
           failure(@"网络异常");
           [[self allSessionTask] removeObject:task];

       }];

       sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
       return sesstionTask;

}


//GET  header
+(NSURLSessionTask *)GET:(NSString *)url body:(NSDictionary *)dic head:(nullable NSDictionary <NSString *, NSString *> *)head success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{
    //    [session.requestSerializer setValue:@"" forHTTPHeaderField:@""];
    
    
    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;
 
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    session.responseSerializer = response;
    [session.requestSerializer setTimeoutInterval:10];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];

    NSString * time = [TKLTools getNomeTimeData];
    NSMutableDictionary * headDic = [NSMutableDictionary dictionary];
        [dic setValue:@"Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==" forKey:@"Authorization"];
        [dic setValue:time forKey:@"timestamp"];
        [dic setValue:@"login" forKey:@"operationDesc"];
        [dic setValue:@"1" forKey:@"requestKey"];
    
    
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    NSURLSessionTask *sesstionTask =  [session GET:url parameters:dic headers:headDic progress:^(NSProgress * _Nonnull downloadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ MBProgressHUD  showError:@"连接服务器出错" toView:[UIApplication sharedApplication].keyWindow];
        NSLog(@"%@",error);
//        failure(@"网络异常");
        [[self allSessionTask] removeObject:task];
    }];

    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
}



//GET
+(NSURLSessionTask *)GET:(NSString *)url body:(NSDictionary *)dic success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{

    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = NO;
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = response;
    [session.requestSerializer setTimeoutInterval:10];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    //设置header
    NSString * timestr = [TKLTools getNomeTimeData];
    [session.requestSerializer setValue:@"Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==" forHTTPHeaderField:@"Authorization"];
    [session.requestSerializer setValue:@"1" forHTTPHeaderField:@"requestKey"];
//    NSString * timestr = [tklTools getNomeTimeData];
    [session.requestSerializer setValue:timestr forHTTPHeaderField:@"timestamp"];
    [session.requestSerializer setValue:@"login" forHTTPHeaderField:@"operationDesc"];
    NSLog(@"%@",session.requestSerializer.HTTPRequestHeaders);
    
    NSDictionary * header = @{@"Authorization":@"Basic TlNUQ0FQUDphbXR1V0d0SVFtSlZkMW8wWW04eU1VMTZVVlExZHowOQ==",@"timestamp":timestr,@"operationDesc":@"ligin",@"requestKey":@"1"};
    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    NSURLSessionTask *sesstionTask =  [session GET:url parameters:dic headers:header progress:^(NSProgress * _Nonnull downloadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);

        [[self allSessionTask] removeObject:task];
    }];

    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
}

//PUT
+(NSURLSessionTask *)PUT:(NSString *)url body:(NSDictionary *)dic success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{

    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.responseSerializer = response;
    [session.requestSerializer setTimeoutInterval:10];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSLog(@"%@",dic);
    //设置header

//    [session.requestSerializer setValue:@"" forHTTPHeaderField:@""];

    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;


    NSURLSessionTask *sesstionTask = [session PUT:url parameters:dic headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        failure(@"网络异常");
        [[self allSessionTask] removeObject:task];
    }];

    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
}

//DELETE
+(NSURLSessionTask *)DELETE:(NSString *)url body:(NSDictionary *)dic success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{

    AFJSONResponseSerializer *response = [AFJSONResponseSerializer serializer];
    response.removesKeysWithNullValues = YES;

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = response;
    [session.requestSerializer setTimeoutInterval:10];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
  NSString * headerStr = [NSString stringWithFormat:@"%@",[stand objectForKey:@"token"]] ;
    //设置header

    [session.requestSerializer setValue:headerStr forHTTPHeaderField:@"Authorization"];

    // 打开状态栏的等待菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;


    NSURLSessionTask *sesstionTask = [session DELETE:url parameters:dic headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        failure(@"网络异常");
        [[self allSessionTask] removeObject:task];
    }];
    sesstionTask ? [[self allSessionTask] addObject:sesstionTask] : nil;
    return sesstionTask;
}



//上传图片 表单上传
+(void)photo:(NSString *)url body:(NSDictionary *)dic photoData:(NSData *)data fileName:(NSString *)name success:(void(^)(NSDictionary *responseObject))success failure:(void(^)(NSString *error))failure{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session.requestSerializer setTimeoutInterval:10];

    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    [session POST:url parameters:dic headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@_photo%@.png",name,str];

        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success(responseObject);
        [[self allSessionTask] removeObject:task];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"数据请求失败");
        [[self allSessionTask] removeObject:task];

    }];
}


#pragma mark 监测网络请求
+(void)AFNetworkStatus:(void(^)(NSInteger state))state{

    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络状态");
                   state(0);
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                 state(0);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"蜂窝数据网");
                 state(1);
                netState = @"4G";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                 state(1);
                netState = @"WIFI";
                break;
            default:
                break;
        }
    }];

}

+ (BOOL)isNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}

+ (BOOL)isWWANNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWWAN;
}

+ (BOOL)isWiFiNetwork {
    return [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
}

//清除当前所有的线程
+ (void)cancelAllRequest {
    // 锁操作
    @synchronized(self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            [task cancel];
        }];
        [[self allSessionTask] removeAllObjects];
    }
}
//清除当前的线程
+ (void)cancelRequestWithURL:(NSString *)URL {
    if (!URL) { return; }
    @synchronized (self) {
        [[self allSessionTask] enumerateObjectsUsingBlock:^(NSURLSessionTask  *_Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([task.currentRequest.URL.absoluteString hasPrefix:URL]) {
                [task cancel];
                [[self allSessionTask] removeObject:task];
                *stop = YES;
            }
        }];
    }
}

/**
 存储着所有的请求task数组
 */
+ (NSMutableArray *)allSessionTask {
    if (!_allSessionTask) {
        _allSessionTask = [[NSMutableArray alloc] init];
    }
    return _allSessionTask;
}



@end
